/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * jifAdministrarTipos.java
 *
 * Created on 18-nov-2010, 7:45:20
 */

package Suministros;

import administracion.delegate.GestionPedidosDelegate;
import administracion.helper.Utiles_MensajesDialogo;
import administracion.helper.Utiles_Tabla;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import org.jdesktop.beansbinding.AutoBinding;
import org.jdesktop.beansbinding.BindingGroup;
import org.jdesktop.beansbinding.ELProperty;
import org.jdesktop.swingbinding.JTableBinding;
import org.jdesktop.swingbinding.SwingBindings;
import suministros.ejb30.TO.TipoTO;

/**
 *
 * @author Diana
 */
public class jifAdministrarTipos extends javax.swing.JInternalFrame {
     private JTableBinding jTableBinding;
     List<TipoTO> listaTipo= new ArrayList<TipoTO>();
     List<TipoTO> listaTipoEliminar= new ArrayList<TipoTO>();
     List<TipoTO> listaTipoAgregar= new ArrayList<TipoTO>();
    /** Creates new form jifAdministrarTipos */
    public jifAdministrarTipos(JFrame padre) {
        initComponents();
        this.llenarComboTabla();
    }
 private void llenarComboTabla() {
        List listaTipos1 = null;
        List listaTipos_cbo1 = this.cboBeanBindingTipoTabla1.getLista();
        listaTipos_cbo1.clear();
        try
        {
          listaTipos1 = GestionPedidosDelegate.getInstance().getComboTablaTipo();

          this.cboBeanBindingTipoTabla1.setLista(listaTipos1);
          this.bindingGroup.bind();
          this.jcbTablaTipo.updateUI();
          this.jcbTablaTipo.setSelectedIndex(-1);
        } catch (Exception ex) {
          Utiles_MensajesDialogo.mensajeAlerta("Error al obtener Tipos\n" + ex.getMessage());
          ex.printStackTrace();
          Logger.getLogger(jifRegistrarSuministros.class.getName()).log(Level.SEVERE, null, ex);
        }
      }
 public void obtenerDatos(){
     listaTipo.clear();
     listaTipoAgregar.clear();
     if(this.jcbTablaTipo.getSelectedIndex()>=0){
        String tipo=this.jcbTablaTipo.getSelectedItem().toString();
        try {
          listaTipo=  GestionPedidosDelegate.getInstance().getListaTiposTabla(tipo);
          actualizarTabla();
          if(listaTipo.isEmpty()){
               Utiles_MensajesDialogo.mensajeAlerta("No se han encontrado tipos");
          }
        } catch (Exception ex) {
            Logger.getLogger(jifAdministrarTipos.class.getName()).log(Level.SEVERE, null, ex);
        }
     }

 }
  public void actualizarTabla(){
    this.bindingGroup = new BindingGroup();
    this.jTableBinding = SwingBindings.createJTableBinding(AutoBinding.UpdateStrategy.READ, listaTipo, this.jTable1);

    JTableBinding.ColumnBinding columnBinding0 = this.jTableBinding.addColumnBinding(ELProperty.create("${id_tabla_tipo}"));

    columnBinding0.setColumnName("Codigo");
    columnBinding0.setColumnClass(String.class);
    columnBinding0.setEditable(false);

    JTableBinding.ColumnBinding columnBinding1 = this.jTableBinding.addColumnBinding(ELProperty.create("${tabla}"));

    columnBinding1.setColumnName("Descripcion");
    columnBinding1.setColumnClass(String.class);
    columnBinding1.setEditable(false);

    JTableBinding.ColumnBinding columnBinding2 = this.jTableBinding.addColumnBinding(ELProperty.create("${descripcion_campo}"));

    columnBinding2.setColumnName("Descripcion Campo");
    columnBinding2.setColumnClass(String.class);
    columnBinding2.setEditable(false);

    JTableBinding.ColumnBinding columnBinding3 = this.jTableBinding.addColumnBinding(ELProperty.create("${codigo}"));

    columnBinding3.setColumnName("Codigo valor");
    columnBinding3.setColumnClass(String.class);
    columnBinding3.setEditable(false);

    JTableBinding.ColumnBinding columnBinding4 = this.jTableBinding.addColumnBinding(ELProperty.create("${descripcion_valor}"));

    columnBinding4.setColumnName("Descripcion valor");
    columnBinding4.setColumnClass(String.class);
    columnBinding4.setEditable(false);



    this.bindingGroup.addBinding(this.jTableBinding);
    this.bindingGroup.bind();
     try {
         int[] porcentajes= {10,20,20,25,25};
          Utiles_Tabla.definirAnchoColumnasJTable(this.jTable1, porcentajes);
          // MiTablePrint.autoSizeTableColumns(jtDetalleSuministro);
        } catch (Exception ex) {
            Logger.getLogger(jifConsultarSuministro.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
   public void llenarTabla(TipoTO tipot){
      boolean estado=true;
      for(TipoTO tip: this.listaTipo){
          if(tip.getCodigo().compareTo(tipot.getCodigo())==0){
               estado=false;
          }
      }
      if(estado){
           this.listaTipoAgregar.add(tipot);
           this.listaTipo.add(tipot);
           this.actualizarTabla();
      }
      else{
          Utiles_MensajesDialogo.mensajeAlerta("El codigo ya ha sido ingresado");
      }

   }
    private void eliminarFila() {
        String id_sumi = this.jTable1.getValueAt(this.jTable1.getSelectedRow(), 0).toString().trim();

        for (TipoTO det : this.listaTipo) {
          if (det.getId_tabla_tipo().toString().equalsIgnoreCase(id_sumi)) {
            this.listaTipo.remove(det);
            this.listaTipoEliminar.add(det);
            break;
          }
        }
        actualizarTabla();
      }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        cboBeanBindingTipoTabla1 = new administracion.BeanBinding.CboBeanBindingTipoTabla();
        jLabel1 = new javax.swing.JLabel();
        jcbTablaTipo = new javax.swing.JComboBox();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jbtCancelar = new javax.swing.JButton();
        jbtAceptar = new javax.swing.JButton();
        jbtAgregar1 = new javax.swing.JButton();
        jbEliminaDetalle = new javax.swing.JButton();

        setTitle("ADMINISTRACION DE TIPOS");

        jLabel1.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        jLabel1.setText("TABLA");

        org.jdesktop.beansbinding.ELProperty eLProperty = org.jdesktop.beansbinding.ELProperty.create("${lista}");
        org.jdesktop.swingbinding.JComboBoxBinding jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, cboBeanBindingTipoTabla1, eLProperty, jcbTablaTipo);
        bindingGroup.addBinding(jComboBoxBinding);

        jcbTablaTipo.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jcbTablaTipoItemStateChanged(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Detalles de Tipos", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 11), new java.awt.Color(0, 0, 255))); // NOI18N

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "CODIGO", "TABLA", "DESCRIPCION CAMPO", "CODIGO CAMPO", "DESCRIPCION VALOR"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 507, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 263, Short.MAX_VALUE)
                .addContainerGap())
        );

        jbtCancelar.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        jbtCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconoscomb/16x16ozygen/actions/button_cancel.png"))); // NOI18N
        jbtCancelar.setMnemonic('C');
        jbtCancelar.setText("CERRAR");
        jbtCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtCancelarActionPerformed(evt);
            }
        });

        jbtAceptar.setFont(new java.awt.Font("Arial", 1, 12));
        jbtAceptar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconoscomb/16x16ozygen/actions/button_ok.png"))); // NOI18N
        jbtAceptar.setMnemonic('A');
        jbtAceptar.setText("ACEPTAR");
        jbtAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtAceptarActionPerformed(evt);
            }
        });
        jbtAceptar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jbtAceptarKeyPressed(evt);
            }
        });

        jbtAgregar1.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        jbtAgregar1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconoscomb/16x16ozygen/actions/add.png"))); // NOI18N
        jbtAgregar1.setMnemonic('A');
        jbtAgregar1.setText("AGREGAR");
        jbtAgregar1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtAgregar1ActionPerformed(evt);
            }
        });

        jbEliminaDetalle.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
        jbEliminaDetalle.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconoscomb/16x16ozygen/actions/remove.png"))); // NOI18N
        jbEliminaDetalle.setMnemonic('E');
        jbEliminaDetalle.setText("ELIMINAR");
        jbEliminaDetalle.setToolTipText("Eliminar el detalle seleccionado");
        jbEliminaDetalle.setEnabled(false);
        jbEliminaDetalle.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        jbEliminaDetalle.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbEliminaDetalleActionPerformed(evt);
            }
        });
        jbEliminaDetalle.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jbEliminaDetalleKeyPressed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(14, 14, 14)
                        .addComponent(jLabel1)
                        .addGap(18, 18, 18)
                        .addComponent(jcbTablaTipo, 0, 240, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jbtAgregar1, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jbEliminaDetalle))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(155, 155, 155)
                        .addComponent(jbtAceptar)
                        .addGap(18, 18, 18)
                        .addComponent(jbtCancelar)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jbEliminaDetalle)
                        .addComponent(jbtAgregar1))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jcbTablaTipo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel1)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jbtCancelar)
                    .addComponent(jbtAceptar))
                .addContainerGap())
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jcbTablaTipoItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jcbTablaTipoItemStateChanged
       this.obtenerDatos();
    }//GEN-LAST:event_jcbTablaTipoItemStateChanged

    private void jbtCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtCancelarActionPerformed
        int res = javax.swing.JOptionPane.showConfirmDialog( this,"Esta seguro de salir?",
                "Confirmar",javax.swing.JOptionPane.YES_NO_OPTION );
        if(res==javax.swing.JOptionPane.YES_OPTION){
            this.dispose();
        }
}//GEN-LAST:event_jbtCancelarActionPerformed

    private void jbtAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtAceptarActionPerformed
        int res = javax.swing.JOptionPane.showConfirmDialog( this,"Esta seguro que desea modificar el grupo de suministro ?",
                "Confirmar",javax.swing.JOptionPane.YES_NO_OPTION );
        if(res==javax.swing.JOptionPane.YES_OPTION){
                try {
                     for(TipoTO tipo: listaTipoAgregar){
                         GestionPedidosDelegate.getInstance().insertarTipo(tipo);
                     }
                     for(TipoTO tipo: listaTipoEliminar){
                         GestionPedidosDelegate.getInstance().insertarTipo(tipo);
                     }
                    Utiles_MensajesDialogo.mensajeExito();
                    this.listaTipo.clear();
                    this.listaTipoAgregar.clear();
                } catch (Exception ex) {
                    Utiles_MensajesDialogo.mensajeError("No se ha podido registrar el ingreso");
                }
         }
}//GEN-LAST:event_jbtAceptarActionPerformed

    private void jbtAceptarKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jbtAceptarKeyPressed
        if(KeyEvent.VK_ENTER == evt.getKeyCode() ||KeyEvent.VK_TAB == evt.getKeyCode()  ){
            this.jbtAceptar.doClick();
        }
}//GEN-LAST:event_jbtAceptarKeyPressed

    private void jbtAgregar1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtAgregar1ActionPerformed
        int selec=this.jTable1.getSelectedRow();
        if(this.jTable1.getRowCount()>0){
            String tabla=this.jTable1.getValueAt(0, 1).toString();
            String descripcion=this.jTable1.getValueAt(0, 2).toString();
            jdAgregarTipo dialog = new jdAgregarTipo(this,null,true,tabla, descripcion, false);
            dialog.setLocationRelativeTo(null);
            dialog.setVisible(true);
        } else{
            String tabla=this.jcbTablaTipo.getSelectedItem().toString();
            String descripcion="";
            jdAgregarTipo dialog = new jdAgregarTipo(this,null,true,tabla, descripcion, true);
            dialog.setLocationRelativeTo(null);
            dialog.setVisible(true);
        }
    }//GEN-LAST:event_jbtAgregar1ActionPerformed

    private void jbEliminaDetalleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbEliminaDetalleActionPerformed

        try {
            if (this.jTable1.getSelectedRow() < 0) {
                Utiles_MensajesDialogo.mensajeError("Debe elegir un detalle");
                return;
            }
            if (Utiles_MensajesDialogo.mensajeConfirmacion("Esta seguro de eliminar el detalle?"))
                eliminarFila();
        } catch (Exception e) {
            e.printStackTrace();
        }
}//GEN-LAST:event_jbEliminaDetalleActionPerformed

    private void jbEliminaDetalleKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jbEliminaDetalleKeyPressed

        if (evt.getKeyCode() == KeyEvent.VK_ENTER ){
            this.jbEliminaDetalle.doClick();
        }
}//GEN-LAST:event_jbEliminaDetalleKeyPressed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private administracion.BeanBinding.CboBeanBindingTipoTabla cboBeanBindingTipoTabla1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JButton jbEliminaDetalle;
    public javax.swing.JButton jbtAceptar;
    private javax.swing.JButton jbtAgregar1;
    private javax.swing.JButton jbtCancelar;
    private javax.swing.JComboBox jcbTablaTipo;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables

}
